package com.ch.light.web.service.impl;

import com.ch.light.mybatis.ParamFilter;
import com.ch.light.web.dao.LoginLogDao;
import com.ch.light.web.mapper.LoginLogMapper;
import com.ch.light.web.model.LoginLog;
import com.ch.light.web.service.LoginLogService;

import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

@Service
public class LoginLogServiceImpl implements LoginLogService {

    @Resource
    private LoginLogMapper loginLogMapper;

    @Override
    public void add(LoginLog loginLog) {
        checkNotNull(loginLog, "登录日志不能为空");
        loginLogMapper.insertSelective(loginLog);
    }

    @Override
    public void delete(Long[] ids) {
        checkArgument(ids != null && ids.length > 0, "登录日志编号不能为空");
        for (Long id : ids) {
            loginLogMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public List<LoginLog> getList(ParamFilter paramFilter) {
        int pageNum = paramFilter.getPage().getPageNo();
        int pageSize = paramFilter.getPage().getPageSize();
        PageHelper.startPage(pageNum, pageSize, true, false, false);
        Example example = new Example(LoginLog.class);
        Map<String, Object> param = paramFilter.getParam();
        if (param != null) {
            Example.Criteria criteria = example.createCriteria();
            String username = (String) param.get("loginAccount");
            String loginAt = (String) param.get("loginTime");

            if (!StringUtils.isEmpty(username)) {
                criteria.andEqualTo("loginAccount", username);
            }
            if (!StringUtils.isEmpty(loginAt)) {
                criteria.andCondition("DATE_FORMAT(LOGIN_TIME, '%Y-%m-%d') = '" + loginAt + "'");
            }
        }
        example.setOrderByClause("LOGIN_TIME DESC");
        return loginLogMapper.selectByExample(example);
    }
}
